﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace JWTServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private IConfiguration _configuration;

        public AuthController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [AllowAnonymous]
        [HttpGet("Login")]
        public IActionResult Login(string userName, string pwd)
        {

            JWTTokenOptions tokenOptions = new JWTTokenOptions();
            _configuration.Bind("JWTTokenOptions", tokenOptions);

            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd))
            {
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, "张三"),
                    new Claim(JwtRegisteredClaimNames.Email, "123456789@qq.com"),
                    new Claim(JwtRegisteredClaimNames.Sub, "D21D099B-B49B-4604-A247-71B0518A0B1C"),
                    new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(10)).ToUnixTimeSeconds()}"),
                    new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                    new Claim("username",userName)
                };


                #region 对称可逆加密
                var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)), SecurityAlgorithms.HmacSha256); 
                #endregion

                #region 非对称可逆加密
                //string keyDir = Directory.GetCurrentDirectory();
                //if (!RSAHelper.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams))
                //{
                //    keyParams = RSAHelper.GenerateAndSaveKey(keyDir);
                //}
                //var signingCredentials = new SigningCredentials(new RsaSecurityKey(keyParams), SecurityAlgorithms.RsaSha256Signature); 
                #endregion

                var token = new JwtSecurityToken(
                    issuer: tokenOptions.Issuer,
                    audience: tokenOptions.Audience,
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    //signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                    signingCredentials: signingCredentials
                );

                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                });
            }
            else
            {
                return BadRequest(new { message = "用户名或密码不能为空" });
            }
        }
    }
}
